package com.zj.controller;

import com.zj.GeneratorApp;
import com.zj.bean.SsmConfig;
import com.zj.job.SsmJob;
import com.zj.util.JsonUtil;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.GridPane;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class SsmCtl {
    public TextField projectNameInpt;
    public TextField userNameInpt;
    public TextField jarPathInpt;
    public TextField apiPathInpt;
    public Button startBtn;
    public TextArea logArea;
    public DirectoryChooser fileChooser;
    public FileChooser jarChooser;
    public GridPane gridPane;
    public AnchorPane topPane;
    public TextField projectDirInpt;
    public TextField apiPackageInpt;
    public TextField basePackageInpt;
    public TextField ormPathInpt;
    public TextField servicePathInpt;
    public TextField databaseInpt;
    public TextField passwordInpt;
    public TextField jdbcUrlInpt;
    public TextArea tableStrInpt;

    public static Map<String, File> PROJECT_MAP = new HashMap<>();
    public ComboBox navContext;
    public TextField modelPathInpt;
    private File currentConfigFile;
    private SsmConfig ssmConfig=new SsmConfig();


    public void log(final String log){
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                logArea.appendText(log);
                logArea.appendText("\n");
            }
        });
    }
    public void cleanLog(){
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                logArea.setText("");
            }
        });
    }

    public void alert(String msg){
        Alert alert = new Alert(Alert.AlertType.WARNING);
        alert.setTitle("提示");
        alert.setHeaderText(msg);
        alert.showAndWait();
    }

    public void openChooseJar(ActionEvent actionEvent){
        if (jarChooser == null) {
            jarChooser=new FileChooser();
        }
        jarChooser.setTitle("选择Jar");
        File jarFile=jarChooser.showOpenDialog(GeneratorApp.primaryStage);
        if (jarFile != null) {
            jarPathInpt.setText(jarFile.getAbsolutePath());
            log(jarFile.getAbsolutePath());
        }
    }

    public void openChooseFile(ActionEvent actionEvent) {
        if (fileChooser == null) {
            fileChooser=new DirectoryChooser();
        }
        fileChooser.setTitle("选择工作目录");
        File folder=fileChooser.showDialog(GeneratorApp.primaryStage);

        if(folder!=null){
            Object obj=actionEvent.getSource();
            Button srcBtn=(Button)obj;
            String name=srcBtn.getId();
            switch (name) {
                case "chooseOrmBtn":ormPathInpt.setText(folder.getAbsolutePath());break;
                case "chooseProjectBtn":projectDirInpt.setText(folder.getAbsolutePath());break;
                case "chooseApiBtn":apiPathInpt.setText(folder.getAbsolutePath());break;
                case "chooseServiceBtn":servicePathInpt.setText(folder.getAbsolutePath());break;
                case "chooseModelBtn":modelPathInpt.setText(folder.getAbsolutePath());break;
                default:;
            }
            log(folder.getAbsolutePath());
        }
    }



    public void startCrawler(ActionEvent actionEvent) {
        String projectName=projectNameInpt.getText();
        String userName=userNameInpt.getText();
        String jarPath=jarPathInpt.getText();
        String apiPath=apiPathInpt.getText();
        String projectDir=projectDirInpt.getText();
        String jdbcUrl=jdbcUrlInpt.getText();

        String apiPackage=apiPackageInpt.getText();
        String basePackage=basePackageInpt.getText();
        String ormPath=ormPathInpt.getText();
        String servicePath=servicePathInpt.getText();
        String database=databaseInpt.getText();
        String password=passwordInpt.getText();
        String tableStr=tableStrInpt.getText();
        String modelPath=modelPathInpt.getText();

        if (StringUtils.isEmpty(apiPackage)) {
            alert("请输入Api包!");
            return;
        }
        if (StringUtils.isEmpty(basePackage)) {
            alert("请输入基本包!");
            return;
        }
        if (StringUtils.isEmpty(ormPath)) {
            alert("请输入ORM目录!");
            return;
        }
        if (StringUtils.isEmpty(servicePath)) {
            alert("请输入Service目录!");
            return;
        }
        if (StringUtils.isEmpty(database)) {
            alert("请输入数据库名称!");
            return;
        }
        if (StringUtils.isEmpty(password)) {
            alert("请输入密码!");
            return;
        }
        if (StringUtils.isEmpty(projectName)) {
            alert("请输入项目名称!");
            return;
        }
        if (StringUtils.isEmpty(projectName)) {
            alert("请输入项目!");
            return;
        }

        if (StringUtils.isEmpty(projectName)) {
            alert("请输入项目!");
            return;
        }

        if (StringUtils.isEmpty(userName)) {
            alert("请输入用户名!");
            return;
        }

        if (StringUtils.isEmpty(jarPath)) {
            alert("请输入Jar路径!");
            return;
        }

//        if (StringUtils.isEmpty(apiPath)) {
//            alert("请选择工作目录!");
//            return;
//        }
        if (StringUtils.isEmpty(tableStr)) {
            alert("请输入表名, 以空格隔开!");
            return;
        }
        if (tableStr.contains(",")) {
            alert("请输入表名, 以空格隔开!");
            return;
        }

        log("参数验证完成。。。");
        ssmConfig.setProjectDir(projectDir);
        ssmConfig.setJdbcUrl(jdbcUrl);
        ssmConfig.setUserName(userName);
        ssmConfig.setPassword(password);
        ssmConfig.setProjectName(projectName);
        ssmConfig.setConnectorPath(jarPath);
        ssmConfig.setControllerJavaPath(apiPath);
        ssmConfig.setControllerPackage(apiPackage);
        ssmConfig.setBasePackage(basePackage);
        ssmConfig.setDatabase(database);
        ssmConfig.setServiceJavaPath(servicePath);
        ssmConfig.setOrmJavaPath(ormPath);
        ssmConfig.setTableStr(tableStr);
        ssmConfig.setModelPath(modelPath);
        ssmConfig.setLastUseTime(System.currentTimeMillis());
        cleanLog();
        log(JsonUtil.obj2String(ssmConfig));


        File configFile=currentConfigFile;
        try {
            FileUtils.writeStringToFile(configFile, JsonUtil.obj2String(ssmConfig),"utf-8");
        } catch (IOException e) {
            e.printStackTrace();
        }


        new SsmJob(ssmConfig,this).start();

    }

    @FXML
    public void initialize(){
//        Color color=Color.web("#4169E1");
//        Color color=Color.rgb(0,67,151);
//
//        gridPane.setBackground(new Background(new BackgroundFill(color,null,null)));
//        topPane.setBackground(new Background(new BackgroundFill(color,null,null)));

//        System.out.println("initialize");

        File confDir = new File("./conf.d");

        if(!confDir.exists()){
            System.out.println("no config directory!");
            return;
        }

        File[] fileList = confDir.listFiles();
        if(fileList==null || fileList.length == 0){
            System.out.println("no config file!");
            return;
        }
        //默认打开最近打开的
        int lastUseIndex=0;
        long lastTime=0;
        for (File configFile : fileList) {
            try {
                String json = FileUtils.readFileToString(configFile, "utf-8");
                SsmConfig config = JsonUtil.toObject(json, SsmConfig.class);
                PROJECT_MAP.put(config.getProjectName(), configFile);
                navContext.getItems().add(config.getProjectName());
                if (config.getLastUseTime() != null && config.getLastUseTime() > lastTime) {
                    lastTime=config.getLastUseTime();
                    lastUseIndex=navContext.getItems().size()-1;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

        ChangeProject changeListener= new ChangeProject();
        navContext.setOnAction(changeListener);
        if (PROJECT_MAP.size() > 0) {
            navContext.getSelectionModel().select(lastUseIndex);
            changeListener.handle(null);
        }
    }

    public void setInputValue(File configFile){
        String json = null;
        try {
            json = FileUtils.readFileToString(configFile, "utf-8");
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
        SsmConfig config = JsonUtil.toObject(json, SsmConfig.class);
        if (config != null) {
            projectDirInpt.setText(config.getProjectDir());
            jarPathInpt.setText(config.getConnectorPath());
            jdbcUrlInpt.setText(config.getJdbcUrl());
            userNameInpt.setText(config.getUserName());
            apiPathInpt.setText(config.getControllerJavaPath());
            projectNameInpt.setText(config.getProjectName());
            apiPackageInpt.setText(config.getControllerPackage());
            basePackageInpt.setText(config.getBasePackage());
            ormPathInpt.setText(config.getOrmJavaPath());
            servicePathInpt.setText(config.getServiceJavaPath());
            databaseInpt.setText(config.getDatabase());
            passwordInpt.setText(config.getPassword());
            tableStrInpt.setText(config.getTableStr());
            modelPathInpt.setText(config.getModelPath());

            ssmConfig.setBaseMapper(config.getBaseMapper());
            ssmConfig.setBaseService(config.getBaseService());
            ssmConfig.setBaseServiceImpl(config.getBaseServiceImpl());
            ssmConfig.setBaseController(config.getBaseController());
        }
    }

    class ChangeProject<ActionEvent> implements EventHandler {

        @Override
        public void handle(Event event) {
            String key= navContext.getSelectionModel().getSelectedItem().toString();
            currentConfigFile=PROJECT_MAP.get(key);
            setInputValue(PROJECT_MAP.get(key));
        }
    }
}
